How can I fix 'IndexError: list index out of range' in my Python function while keeping [0]